package org.example.datajpa2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.example.datajpa2.Status;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;

@SpringBootApplication
public class DataJpa2Application implements CommandLineRunner {

    @Autowired
    StatusRepository statusRepository;

    public static void main(String[] args) {
        SpringApplication.run(DataJpa2Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        Status status = new Status();
        status.setContent("Hello World");
        status.setAuthor("huangzhuoyan");
        statusRepository.save(status);

        Optional<Status> s = statusRepository.findById(1);
        Status s1 = s.orElseThrow();
        s1.setAuthor("JJJJ");
        statusRepository.save(s1);

        List<Status> result = statusRepository.findByAuthor("JJJJ");
        System.out.println("findByAuthor result size:"+result.size());

//        status = new Status();
//        status.setAuthor("John");
//        status.setContent("Hello World");
//        status.setLikes(9);
//        statusRepository.save(status);
//        result = statusRepository.findByLikesGreaterThan(9);
//        System.out.println("findByLikes result size:1"+result.size());

        status = new Status();
        status.setAuthor("Peter");
        status.setContent("Blog2");
        statusRepository.save(status);
        result = statusRepository.findByContentContaining("blog");
        System.out.println("findByContentContaining result size:"+result.size());

        status = new Status();
        status.setAuthor("Peter");
        status.setContent("Blog3");
        status.setCreateTime(Timestamp.valueOf("2024-11-11 11:11:11"));
        statusRepository.save(status);
        result = statusRepository.findByAuthorAndCreateTimeBeforeOrderByCreateTime("Peter",new Timestamp(System.currentTimeMillis()));
        System.out.println("findByAuthorAndCreateTimeBefore result size:"+result.size());

        result = statusRepository.findByMonth(11);
        System.out.println("findByMonth result size:"+result.size());

        int row = statusRepository.deleteByAuthor("Peter");
        System.out.println("deleteByAuthor result row:"+row);

        long count = statusRepository.count();
        System.out.println("count:"+count);

        PageRequest p = PageRequest.of(0,2, Sort.by("createTime").descending());
        Page<Status> result2 = statusRepository.findAll(p);
        System.out.println("findAll result size:"+result2.getSize());
    }
}
